#include"tools/list.h"

void list_init(list* list)
{
    list->first=list->last = (list_node*)0;
    list->count=0;
}

void list_insert_first(list* list,list_node* node)
{
    node->next=list->first;
    node->prev=(list_node*)0;

    if(list_empty(list))
    {
        list->last=list->first=node;
    }
    else
    {
        list->first->prev=node;
        list->first=node;
    }
    list->count++;
}
void list_insert_last(list* list,list_node* node)
{
    node->prev=list->last;
    node->next=(list_node*)0;
    if(list_empty(list))
    {
        list->last=list->first=node;
    }
    else
    {
        list->last->next=node;
        list->last=node;
    }
    list->count++;
}

list_node* list_remove_first(list* list)
{
    if(list_empty(list))
    {
        return (list_node*)0;
    }
    list_node* remove_node=list->first;
    list->first=remove_node->next;
    if(list->first==(list_node*)0)
    {
        list->last=(list_node*)0;
    }
    else
    {
        list->first->prev=(list_node*)0;     
    }
    remove_node->prev=(list_node*)0;
    remove_node->next=(list_node*)0;
    list->count--;
    return remove_node;
}

list_node* list_remove(list* list,list_node* node)
{
    if(node==list->first)
    {
        list->first=node->next;
    }

    if(node==list->last)
    {
        list->last=node->prev;
    }

    if(node->prev)
    {
        node->prev->next=node->next;
    }

    if(node->next)
    {
        node->next->prev=node->prev;
    }
    list->count--;

    return node;
}